package com.ts.proj.controller;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.common.constant.ProvinceConstant;
import com.ts.proj.entity.*;
import com.ts.proj.service.ProjectService;
import com.ts.proj.service.SystemGlobalService;
import com.ts.proj.service.SystemMenuService;
import com.ts.proj.service.SystemRoleService;
import com.ts.util.JsonUtils;
import com.ts.util.JurisdictionUtil;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@Slf4j
public class IndexController extends BaseController {
    @Autowired
    private SystemRoleService systemRoleService;
    @Autowired
    private SystemMenuService systemMenuService;
    @Autowired
    private SystemGlobalService systemGlobalService;

    @Autowired
    private ProjectService projectService;

    /**
     * 重定向
     * @return
     */
    @RequestMapping(value = "/")
    public ModelAndView index(){
        ModelAndView mv  = this.getModelAndView();

        //-----------从redis里面查询
        List<SystemGlobalEntity> all = systemGlobalService.findAll();
        SystemGlobalEntity systemGlobalEntity = null;
        if(all.size()!=1){
            systemGlobalEntity = new SystemGlobalEntity();
        }else{
            systemGlobalEntity = all.get(0);
        }
        mv.addObject("entity", systemGlobalEntity);
        //-----------从redis里面查询

        mv.setViewName("login");
        return mv;
    }

    @RequestMapping(value = "/logout_tologout")
    public ModelAndView logout(){
        ModelAndView modelAndView = this.getModelAndView();
        this.getRequest().getSession().removeAttribute(ConsoleConstant.SESSIONUSER);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.RIGHTS);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.ROLEID);
        this.getRequest().getSession().removeAttribute(ConsoleConstant.BTNRIGHTS);

        //-----------从redis里面查询
        List<SystemGlobalEntity> all = systemGlobalService.findAll();
        SystemGlobalEntity systemGlobalEntity = null;
        if(all.size()!=1){
            systemGlobalEntity = new SystemGlobalEntity();
        }else{
            systemGlobalEntity = all.get(0);
        }
        modelAndView.addObject("entity", systemGlobalEntity);
        //-----------从redis里面查询
        modelAndView.setViewName("login");
        return modelAndView;
    }

    @RequestMapping("/main")
    public ModelAndView main(){
        //获取角色以及menu list
        ModelAndView mv = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            String user = (String) this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER);
            SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(user, SystemUserEntity.class);
            Integer roleId = systemUserEntity.getRoleId();
            //通过Role查找rights，在查menu

            List<Integer> roleIdList = new ArrayList<>();
            //roleId表示RightHelper
            for(int i=0;i<500;i++){
                if(RightsHelper.testRights(String.valueOf(roleId),i)){
                    roleIdList.add(i);
                }
            }
            List<SystemRoleEntity> allOrOne = systemRoleService.getSystemRoleEntityListByIds(roleIdList);
            if(allOrOne==null||allOrOne.size()==0){
                mv.setViewName("login");
                return mv;
            }

            List<Integer> ids = new ArrayList<>();
            for(SystemRoleEntity entity : allOrOne){
                //为了防止转成科学计数法，将权限码添加了首位标记：R-页面权限，B-按钮权限
                String rights = entity.getRights().substring(1);
                //通过rights来获取menu
                for(int i=1;i<1000;i++){
                    if(RightsHelper.testRights(rights, i)){
                        ids.add(i);
                    }
                }
            }
            Integer[] idsArray = new Integer[ids.size()];
            for(int i=0;i<ids.size();i++){
                idsArray[i] = ids.get(i);
            }
            Arrays.sort(idsArray);

            //-----------从redis里面查询
            List<SystemGlobalEntity> all = systemGlobalService.findAll();
            SystemGlobalEntity systemGlobalEntity = null;
            if(all.size()!=1){
                systemGlobalEntity = new SystemGlobalEntity();
            }else{
                systemGlobalEntity = all.get(0);
            }
            mv.addObject("entity", systemGlobalEntity);
            //-----------从redis里面查询

            //通过ids查询所有的menu
            mv.addObject("user", systemUserEntity.getNickname());
            mv.addObject("loginName", systemUserEntity.getUsername());
            mv.addObject("count", 1);
            mv.addObject("shortlist", shortList(systemUserEntity.getUserShortCut()));
            mv.addObject("menu", menuLists(systemMenuService.findAllById(idsArray)));
            viewName = "index/main";
        }
        mv.setViewName(viewName);
        return mv;
    }

    /**
     * iframe 跳转页面
     * @return
     */
    @RequestMapping(value="/iframe")
    public ModelAndView mainIframe() {
        ModelAndView mv = this.getModelAndView();

        //获取所有项目


        PageData pd = new PageData();
        pd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        //获取所有项目
        long allProjects = projectService.count(pd);


        //获取所有入库(0)
        pd.put("proState", 0);
        long rukuProjects = projectService.count(pd);

        //获取所有立项(1)
        pd.put("proState", 1);
        long lixiangProjects = projectService.count(pd);

        //获取所有决策(2)
        pd.put("proState", 2);
        long jueceProjects = projectService.count(pd);

        //获取所有投资(3)
        pd.put("proState", 3);
        long touziProjects = projectService.count(pd);

        //获取所有投后(4)
        pd.put("proState", 4);
        long touhouProjects = projectService.count(pd);

        //获取所有退出(5)
        pd.put("proState", 5);
        long tuichuProjects = projectService.count(pd);

        pd.put("proState", -1);
        long errorProjects = projectService.count(pd);

        //获取直投项目
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        param.put("proCategory", 0);
        long zhitouProjects = projectService.count(param);
        param.put("proCategory", 1);
        long jijinProjects = projectService.count(param);



        long[] array = new long[]{rukuProjects,lixiangProjects,jueceProjects,touziProjects,touhouProjects,tuichuProjects};


        mv.addObject("allProjects", allProjects);

        mv.addObject("data", JsonUtils.objectToJson(array));
        mv.addObject("zhitouProjects", zhitouProjects);
        mv.addObject("jijinProjects", jijinProjects);
        mv.addObject("errorProjects", errorProjects);

        List<PageData> allProvinceProjects = projectService.findAllProvinceProjects();
        List<String> proList = Arrays.asList(ProvinceConstant.province);
        List<PageData> result = new ArrayList<>();
        for(String str : proList){
            int count = 0;
            for(PageData p : allProvinceProjects){
                if(str.equals(p.get("province"))){
                    count++;
                }
            }
            PageData tp = new PageData();
            tp.put("name", str);
            tp.put("value", count);
            result.add(tp);
        }

        mv.addObject("provinceList", JsonUtils.objectToJson(result));
        mv.setViewName("index/welcome");
        return mv;
    }

    //直投项目详细列表
    @RequestMapping(value = "/zhitou-list")
    public ModelAndView zhitouMainInfo(){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            modelAndView.addObject("catagory", 0);
            viewName = "business/welcome/project-list";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }
    //基金项目详细列表
    @RequestMapping(value = "/jijin-list")
    public ModelAndView jijinMainInfo(){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            modelAndView.addObject("catagory", 1);
            viewName = "business/welcome/project-list";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    //--------------------------------------------------------------------------//
    private List<PageData> menuLists (List<SystemMenuEntity> systemMenuEntities){
        List<PageData> nodes = new ArrayList<PageData>();
        int i = 0;
        for(SystemMenuEntity menuEntity : systemMenuEntities){
            //获取父目录
            if("0".equals(menuEntity.getParentId())&& InsUpdDelFlagConstant.DELETE_FLAG_N.equals(menuEntity.getDeleteFlag())){
                //获取MENU_ID
                Integer menuId = menuEntity.getId();
                PageData pd = new PageData();
                pd.put("MENU_ID",String.valueOf(menuEntity.getId()));
                pd.put("PARENT_ID",menuEntity.getParentId());
                pd.put("MENU_NAME",menuEntity.getMenuName());
                pd.put("MENU_ICON",menuEntity.getMenuIcon());
                List<PageData> subMenuEntityPageData = new ArrayList<>();
                for(SystemMenuEntity menu: systemMenuEntities){
                    if(menuId == Integer.valueOf(menu.getParentId())&& InsUpdDelFlagConstant.DELETE_FLAG_N.equals(menu.getDeleteFlag())){
                        PageData subPageData = new PageData();
                        subPageData.put("MENU_ID",String.valueOf(menuEntity.getId()));
                        subPageData.put("PARENT_ID",menu.getParentId());
                        subPageData.put("MENU_URL",menu.getMenuURL());
                        subPageData.put("MENU_NAME",menu.getMenuName());
                        subPageData.put("MENU_ICON",menu.getMenuIcon());
                        subPageData.put("ID", i++);
                        subMenuEntityPageData.add(subPageData);
                    }
                }
                pd.put("subMenu",subMenuEntityPageData);
                nodes.add(pd);
            }
        }

        return nodes;
    }

    private List<PageData> shortList(String userShortCut) {

        List<PageData> resultList = new ArrayList<>();
            List<Integer> idsList = new ArrayList<>();
            for(int i=0;i<200;i++){
                if(RightsHelper.testRights(userShortCut.substring(1),i)){
                    idsList.add(i);
                }
            }
            Integer[] idsArray = new Integer[idsList.size()];
                idsList.toArray(idsArray);
            List<SystemMenuEntity> systemMenuList = systemMenuService.findAllById(idsArray);
            for(SystemMenuEntity menu : systemMenuList){
                if(menu.getId()!=null){
                    PageData pageData = new PageData();
                    pageData.put("menuName", menu.getMenuName());
                    pageData.put("menuUrl", "/" + menu.getMenuURL());
                    resultList.add(pageData);
                }

            }

        return resultList;
    }
}
